let stompClient = null;
let username = null;
let selectedUser = null;
let userColors = new Map();

// 颜色生成函数
function getColorForUser(username) {
    if (userColors.has(username)) {
        return userColors.get(username);
    }
    
    let hash = 0;
    for (let i = 0; i < username.length; i++) {
        hash = username.charCodeAt(i) + ((hash << 5) - hash);
    }
    
    const hue = hash % 360;
    const color = `hsl(${hue}, 70%, 95%)`;
    userColors.set(username, color);
    return color;
}

// 用户名生成
function generateUsername() {
    const savedUsername = localStorage.getItem('chatUsername');
    if (savedUsername) {
        return savedUsername;
    }
    const newUsername = 'User' + Math.floor(Math.random() * 9000000000 + 1000000000);
    localStorage.setItem('chatUsername', newUsername);
    return newUsername;
}

// WebSocket 连接
function connect() {
    username = document.getElementById('username').value.trim();
    if (!username) {
        username = generateUsername();
    }
    localStorage.setItem('chatUsername', username);

    const socket = new SockJS('/websocket-chat');
    stompClient = Stomp.over(socket);
    stompClient.connect({}, onConnected, onError);
    
    document.getElementById('login-screen').style.display = 'none';
    document.getElementById('chat-screen').style.display = 'block';

    startHeartbeat();
}

function onConnected() {
    // 先订阅用户列表主题，确保能及时接收用户列表更新
    stompClient.subscribe('/topic/users', onUserListReceived);
    
    // 订阅公共消息
    stompClient.subscribe('/topic/public', onMessageReceived);
    
    // 订阅私人消息
    stompClient.subscribe(`/user/${username}/queue/private`, onMessageReceived);
    
    // 发送加入消息，服务器会响应最新的用户列表
    stompClient.send("/app/chat.register", {}, JSON.stringify({
        sender: username,
        type: 'JOIN'
    }));

    // 立即请求当前用户列表
    stompClient.send("/app/chat.users", {}, {});
}

function onError(error) {
    console.log('连接错误:', error);
    alert('连接失败，正在重新连接...');
    // 尝试重新连接
    setTimeout(connect, 5000);
}

function startHeartbeat() {
    setInterval(() => {
        if (stompClient) {
            stompClient.send("/app/chat.heartbeat", {}, JSON.stringify({
                sender: username,
                type: 'HEARTBEAT'
            }));
        }
    }, 30000); // 每30秒发送一次心跳
}

function onMessageReceived(payload) {
    const message = JSON.parse(payload.body);
    
    // 处理系统消息
    if (message.type === 'JOIN' || message.type === 'LEAVE' || message.type === 'ERROR') {
        const systemMessage = document.createElement('div');
        systemMessage.className = `system-log ${message.type.toLowerCase()}`;
        
        const timestamp = document.createElement('span');
        timestamp.className = 'timestamp';
        timestamp.textContent = new Date().toLocaleTimeString();
        
        const content = document.createElement('span');
        if (message.type === 'JOIN') {
            content.textContent = `${message.sender} 加入了聊天室`;
        } else if (message.type === 'LEAVE') {
            content.textContent = `${message.sender} 离开了聊天室`;
        } else if (message.type === 'ERROR') {
            content.textContent = message.content;
        }
        
        systemMessage.appendChild(timestamp);
        systemMessage.appendChild(content);
        
        const messagesDiv = document.getElementById('messages');
        messagesDiv.appendChild(systemMessage);
        messagesDiv.scrollTop = messagesDiv.scrollHeight;
    }
    
    // 处理聊天消息
    if (message.type === 'CHAT' || message.type === 'FILE') {
        const messageContainer = document.createElement('div');
        messageContainer.className = 'message-container';
        const messageElement = document.createElement('div');
        messageElement.className = 'message';
        
        // 创建消息头部（用户名和时间）
        const messageHeader = document.createElement('div');
        messageHeader.className = 'message-header';
        messageHeader.innerHTML = `
            <span class="sender">${message.sender}${message.receiver ? ' 对 ' + message.receiver + ' 说' : ''}</span>
            <span class="timestamp">${new Date().toLocaleTimeString()}</span>
        `;
        
        // 创建消息气泡
        const messageBubble = document.createElement('div');
        messageBubble.className = 'message-bubble';
        
        // 根据发送者设置不同的样式
        if (message.sender === username) {
            messageBubble.classList.add('sender-message');
            messageBubble.style.backgroundColor = '#e3f2fd';
        } else {
            messageBubble.classList.add('receiver-message');
            messageBubble.style.backgroundColor = getColorForUser(message.sender);
        }
        
        messageBubble.textContent = message.content;
        
        messageElement.appendChild(messageHeader);
        messageElement.appendChild(messageBubble);
        messageContainer.appendChild(messageElement);
        
        const messagesDiv = document.getElementById('messages');
        messagesDiv.appendChild(messageContainer);
        messagesDiv.scrollTop = messagesDiv.scrollHeight;
    }
}

function onUserListReceived(payload) {
    const users = JSON.parse(payload.body);
    const userListDiv = document.getElementById('userList');
    userListDiv.innerHTML = '';
    
    users.forEach(user => {
        const userElement = document.createElement('div');
        userElement.className = 'user-item';
        
        if (user === username) {
            userElement.textContent = `${user} (我)`;
            userElement.style.fontWeight = 'bold';
        } else {
            userElement.textContent = user;
            userElement.onclick = () => selectUser(user);
        }
        
        userListDiv.appendChild(userElement);
    });
}

function selectUser(user) {
    selectedUser = user;
    document.getElementById('currentChat').textContent = 
        `当前聊天: ${user || '群聊'}`;
}

// 页面加载完成后执行
window.onload = function() {
    document.getElementById('username').value = generateUsername();
    connect();
}

// 在现有代码后添加
function sendMessage() {
    const messageContent = document.getElementById('messageInput').value.trim();
    if (messageContent && stompClient) {
        const chatMessage = {
            sender: username,
            content: messageContent,
            type: 'CHAT'
        };
        
        if (selectedUser) {
            chatMessage.receiver = selectedUser;
        }
        
        stompClient.send("/app/chat.send", {}, JSON.stringify(chatMessage));
        document.getElementById('messageInput').value = '';
    }
}

function addEmoji() {
    const messageInput = document.getElementById('messageInput');
    messageInput.value += '😊';
}

// 添加回车发送功能
document.addEventListener('DOMContentLoaded', function() {
    document.getElementById('messageInput').addEventListener('keypress', function(event) {
        if (event.key === 'Enter') {
            event.preventDefault();
            sendMessage();
        }
    });
}); 